package org.l.qiao.connect;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;


public class DataMap {

    private static final Logger LOGGER = Logger.getLogger(DataMap.class);

    @SuppressWarnings({"rawtypes", "unchecked"})
    public boolean Mapping(String name, String value, Object obj) {
        Class objclass = obj.getClass();
        String methodname = "set" + name.substring(0, 1).toUpperCase()
                + name.substring(1);
        Method method;
        try {
            method = objclass.getMethod(methodname, java.lang.String.class);
            method.invoke(obj, value);
        } catch (Exception e) {
            LOGGER.error(String.format("对象映射赋值失败(name=%s,value=%s,class=%s)：",
                    name, value, obj.toString()) + e.getMessage());
            return false;
        }
        return true;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public List Mapping(ResultSet rs, Class obj) {
        List list = new ArrayList();
        if (rs != null) {
            try {
                ResultSetMetaData rsm = rs.getMetaData();
                int i;
                int colmcount = rsm.getColumnCount();
                while (rs.next()) {
                    Object newobj = obj.newInstance();
                    for (i = 1; i <= colmcount; i++) {
                        if (rs.getString(i) != null)
                            Mapping(rsm.getColumnName(i).toLowerCase(),
                                    rs.getString(i), newobj);
                    }
                    list.add(newobj);
                }
            } catch (Exception e) {
                LOGGER.error("数据操作异常：" + e.getMessage());
            }
        }
        return list;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public Object getMapValue(String name, Object object) {
        Class objclass = object.getClass();
        String methodname = "get" + name.substring(0, 1).toUpperCase()
                + name.substring(1);
        Method method;
        Object rs = null;
        try {
            method = objclass.getMethod(methodname);
            rs = method.invoke(object);
        } catch (Exception e) {
            LOGGER.error(String.format("对象映射取值失败(name=%s,class=%s)：", name,
                    object.toString())
                    + e.getMessage());
        }
        return rs;
    }
}
